#!/usr/bin/env python 
# encoding: utf-8 

"""
@author: jiu
@contact: 643562684@qq.com
@file: log.py
@time: 2022/3/3 11:45
"""

import logging
from os import path
import logging.handlers
from datetime import datetime
from Conf.setting import *
from common.read_Ini import Read_InI


class Loggings(object):
    def __init__(self, file_name: str = ' ', file_dir: str = LOG_SAVE_PATH):
        # 格式 记录产生的时间  文件名 函数方法 产生异常的行 等级 信息
        # info 20 debug 10
        log_conf = Read_InI(PROJECT_CONF_SETTING['project']).data['logger']
        # print(log_conf)
        self.logger = logging.getLogger(__name__)
        #  log收集的等级
        self.logger.setLevel(log_conf['collect_level'])
        # 当前时间
        now_date = str(datetime.now().strftime("%Y%m%d")) + ".log"
        formatter = "%(levelname)s - %(asctime)s - %(filename)s - %(funcName)s - [line]:%(lineno)d:   %(message)s"

        if file_name == " ":
            file_name = now_date
        # 默认的格式就是默认的路径加上当前时间的组合
        log_path = path.join(file_dir, file_name)
        # 设置输出格式
        formatter = logging.Formatter(formatter)

        con_fmt = logging.StreamHandler()
        # log 输出的级别
        con_fmt.setLevel(log_conf["output_level"])
        con_fmt.setFormatter(formatter)
        self.logger.addHandler(con_fmt)

        # log文件过大后拆分
        rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=log_path,
                                                                   maxBytes=log_conf['maxbytes'],
                                                                   backupCount=log_conf['backupcount'],
                                                                   encoding='utf-8')

        # 输入文件内格式和等级
        rotatingFileHandler.setFormatter(formatter)
        rotatingFileHandler.setLevel(log_conf["write_file_level"])

        # 添加内容到日志句柄中
        self.logger.addHandler(rotatingFileHandler)


logger = Loggings().logger

